/**
 * JAVACC DEMO 1.0
 */
package com.apache.info.template;

import com.apache.uct.common.ToolsUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import java.io.*;
import java.util.Locale;
import java.util.Map;

/**
 * description:  模板操作辅助类
 *
 * @author Hou Dayu 创建时间：2016-7-8
 */
public class FreemarkerHelper {

    private Logger log = Logger.getLogger(FreemarkerHelper.class);

    private static FreemarkerHelper helper;

    private Configuration freemarker_cfg = null;

    private FreemarkerHelper() {
    }

    public static FreemarkerHelper instance() {
        if (null == helper) {
            helper = new FreemarkerHelper();
        }
        return helper;
    }

    public String getTemplateStr(String templateName, Map mapData) throws Exception {
        Template template = getFreeMarkerCFG().getTemplate(templateName);
        template.setEncoding("UTF-8");

        StringWriter stream = new StringWriter();
        template.process(mapData, stream);
        String sndRtn = stream
                .toString();//FreeMarkerTemplateUtils.processTemplateIntoString(template, mapData);
        return sndRtn;
    }

    public File getTemplateFile(String templateName, Map mapData, String fileName) {
        FileOutputStream fos = null;
        OutputStreamWriter oWriter = null;
        try {
            Template template = getFreeMarkerCFG().getTemplate(templateName);
            template.setEncoding("UTF-8");
            Writer out = null;
            File outFile = new File(fileName);
            fos = new FileOutputStream(outFile);
            oWriter = new OutputStreamWriter(fos, "UTF-8");// 这个地方对流的编码不可或缺，
            out = new BufferedWriter(oWriter);
            template.process(mapData, out);
            return outFile;
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(oWriter);
            IOUtils.closeQuietly(fos);
        }
        return null;
    }

    /**
     * 获取freemarker的配置. freemarker本身支持classpath,目录和从ServletContext获取.
     */
    private Configuration getFreeMarkerCFG() {
        if (null == freemarker_cfg) {
            File templateFile = new File(
                    ToolsUtil.getClassLoaderPath().replaceAll("WEB-INF/classes/", "")
                            + "/template/info/");
            freemarker_cfg = new Configuration();
            try {
                freemarker_cfg.setDirectoryForTemplateLoading(templateFile);
                freemarker_cfg.setEncoding(Locale.CHINA, "UTF-8");
            } catch (IOException e) {
                log.error("Get tempalte error", e);
            }
            freemarker_cfg.setSharedVariable("upper", new UpperFirstMethod());
            //			freemarker_cfg.setSharedVariable("priceStr", new FormatPriceMethod());
            //			freemarker_cfg.setSharedVariable("subString", new SubStringMethod());
            //			freemarker_cfg.setSharedVariable("statusText", new WbdInfoStatusMethod());
        }
        return freemarker_cfg;
    }
}
